<template>
  <div class="container">
    <div class="app-container">
      <div class="addBtn">
        <el-button type="primary" size="mini" @click="dialogVisible = true">添加角色</el-button>
      </div>
      <!-- 数据展示区 -->
      <el-table :data="tableData">
        <!-- 角色 -->
        <el-table-column prop="name" align="center" label="角色" width="200">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editData.name" placeholder size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <!-- 是否启用 -->
        <el-table-column prop="state" align="center" label="是否启用" width="200">
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.state" />
            <span v-else>{{ row.state === 1 ? '已启用' : '未启用' }}</span>
          </template>
        </el-table-column>
        <!-- 描述内容 -->
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editData.description"
              type="textarea"
              :rows="3"
              placeholder="描述内容"
              size="mini"
            />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <!-- 操作控件 -->
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="!row.isEdit">
              <el-button type="text" size="mini" @click="showPermissionDialog(row.id)">分配权限</el-button>
              <el-button type="text" size="mini" @click="editBtn(row)">编辑</el-button>
              <!-- <el-button v-popover:popover5 type="text" size="mini" @click="delBtn(row.id)">删除</el-button> -->
              <el-popconfirm title="确定要删除吗?" style="margin-left: 10px;" @confirm="delBtn(row.id)">
                <el-button slot="reference" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </template>
            <template v-else>
              <el-button type="primary" size="mini" @click="editOkBtn(row)">确定</el-button>
              <el-button type size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-row class="pagintionBox" type="flex" justify="end">
        <el-pagination
          layout="prev, pager, next"
          :current-page="pagePagination.page"
          :page-size="pagePagination.pagesize"
          :total="pagePagination.total"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 添加角色弹出层 -->
    <el-dialog title="添加角色" :visible.sync="dialogVisible" @close="btnCancel">
      <el-form ref="roleForm" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item prop="name" label="活动名称">
          <el-input v-model="formData.name" size="mini" placeholder="清输入角色名称" />
        </el-form-item>
        <el-form-item label="是否启用" prop="state">
          <el-switch v-model="formData.state" active-value="0" inactive-value="1" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="formData.description" type="textarea" rows="3" placeholder="角色描述" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="btnCancel">取 消</el-button>
        <el-button type="primary" @click="btnOk">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 全部权限列表弹出层 分配权限弹出层 -->
    <el-dialog title="分配权限" :visible.sync="permissionDialogVisible">
      <el-tree
        ref="permissionTree"
        :data="permissionData"
        :props="{ label: 'name' }"
        node-key="id"
        :default-checked-keys="permIds"
        show-checkbox
        default-expand-all
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="permissionDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="permissionDialogVisibleBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoleListAPI,
  postRoleAPI,
  putRoleAPI,
  delRoleAPI,
  getRoleDetailsAPI,
  putPermissionRoleAPI
} from '@/api/role'
import { getPermissionDataAPI } from '@/api/permission'
import { transListToTreeData } from '@/utils/index'

export default {
  name: 'Role',
  data() {
    return {
      // 数据
      tableData: [],
      // 分页器相关数据
      pagePagination: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      // 添加角色弹出层
      dialogVisible: false,
      // 表单数据
      formData: {
        name: '',
        description: '',
        state: 0
      },
      // 校验规则
      formRules: {
        name: [
          { required: true, message: '活动名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      // 是否展示分配权限弹出层
      permissionDialogVisible: false,
      // 点击分配角色后保存当前选中的id
      currentId: '',
      // 分配权限弹出层数据
      permissionData: [],
      // 弹出层的选中的数据列表
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取渲染的数据
    async getRoleList() {
      const { rows, total } = await getRoleListAPI(this.pagePagination)
      this.tableData = rows
      this.pagePagination.total = total
      // 为每一项数据添加一个自定义属性 添加一个对象用于存储缓存的数据
      this.tableData.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editData', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 页码改变是重新回去渲染数据
    changePage(page) {
      this.pagePagination.page = page
      // 重新获取数据
      this.getRoleList()
    },
    // 确认新增
    btnOk() {
      this.$refs.roleForm.validate(async valid => {
        if (valid) {
          await postRoleAPI(this.formData)
          this.$message.success('新增成功')
          this.btnCancel()
        }
      })
    },
    // 取消新增
    btnCancel() {
      // 重置表单
      this.$refs.roleForm.resetFields()
      // 关闭弹层
      this.dialogVisible = false
    },
    // 点击进入编辑状态
    editBtn(row) {
      row.isEdit = true
      // 每次点击编辑都让回填的数据位获取过来的数据
      row.editData.name = row.name
      row.editData.state = row.state
      row.editData.description = row.description
    },
    // 确定编辑
    async editOkBtn(row) {
      if (row.editData.name && row.editData.description) {
        await putRoleAPI({ ...row.editData, id: row.id })
        this.$message.success('修改成功')
        // 修改数值
        Object.assign(row, {
          ...row.editData,
          isEdit: false
        })
      } else {
        return this.$message.success('角色/描述不能为空')
      }
    },
    // 点击确定删除按钮
    async delBtn(id) {
      await delRoleAPI(id)
      if (this.tableData.length === 1) {
        this.pagePagination.page--
      }
      this.getRoleList()
      this.$message.success('删除成功')
    },
    // 点击分配权限
    async showPermissionDialog(id) {
      this.currentId = id
      this.permissionData = transListToTreeData(
        await getPermissionDataAPI(id),
        0
      )
      // 点击当前的被选中的数据列表
      const { permIds } = await getRoleDetailsAPI(id)
      this.permIds = permIds
      this.permissionDialogVisible = true
    },
    // 点击分配权限弹出层的确定按钮
    async permissionDialogVisibleBtn() {
      await putPermissionRoleAPI({
        id: this.currentId,
        permIds: this.$refs.permissionTree.getCheckedKeys()
      })
      this.$message.success('分配角色成功')
      this.permissionDialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  .app-container {
    .addBtn {
      padding: 15px;
    }

    .pagintionBox {
      padding: 10px;
    }
  }
}
</style>
